<template>
  <div class="page-container">
    <h1>个人信息修改</h1>
    <div class="content-card">
      <el-form
        ref="profileFormRef"
        :model="profileForm"
        :rules="profileRules"
        label-width="120px"
        class="profile-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="profileForm.username" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="员工ID" prop="id">
              <el-input v-model="profileForm.id" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="profileForm.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="profileForm.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="员工类型" prop="role">
              <el-input v-model="roleText" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :headers="uploadHeaders()"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="profileForm.image" :src="profileForm.image" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            保存修改
          </el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button @click="showPasswordDialog = true">修改密码</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="showPasswordDialog"
      title="修改密码"
      width="400px"
      :before-close="handlePasswordDialogClose"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            placeholder="请输入原密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请确认新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handlePasswordDialogClose">取消</el-button>
          <el-button type="primary" @click="handlePasswordSubmit" :loading="passwordLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
const profileFormRef = ref(null)
const passwordFormRef = ref(null)
const loading = ref(false)
const passwordLoading = ref(false)
const showPasswordDialog = ref(false)

// 上传配置
const uploadUrl = 'http://localhost:8080/api/upload/avatar'
const uploadHeaders = () => ({
  'Token': localStorage.getItem('Token')
})

// 个人信息表单
const profileForm = reactive({
  id: '',
  username: '',
  name: '',
  phone: '',
  role: '',
  image: ''
})

// 员工类型显示文本
const roleText = ref('')

// 根据role值设置显示文本
const updateRoleText = () => {
  switch (profileForm.role) {
    case 1:
    case '1':
      roleText.value = '前台人员'
      break
    case 2:
    case '2':
      roleText.value = '技术人员'
      break
    default:
      roleText.value = '未知类型'
  }
}

// 密码修改表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const profileRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

const validateConfirmPassword = (_rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== passwordForm.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

// 初始化表单数据
const initFormData = () => {
  const userData = localStorage.getItem('user')
  if (userData) {
    try {
      const user = JSON.parse(userData)
      console.log('从localStorage获取用户信息:', user)

      // 根据数据库结构映射字段
      profileForm.id = user.id || ''
      profileForm.username = user.username || ''
      profileForm.name = user.name || ''
      profileForm.phone = user.phone || ''
      profileForm.role = user.role || ''
      profileForm.image = user.image || ''

      // 更新员工类型显示文本
      updateRoleText()
    } catch (error) {
      console.error('解析用户数据失败:', error)
      ElMessage.error('获取用户信息失败')
    }
  } else {
    ElMessage.error('未找到用户信息，请重新登录')
    // 可以选择跳转到登录页面
    // window.location.href = '/login'
  }
}

// 头像上传成功回调
const handleAvatarSuccess = (response) => {
  if (response.code === 200) {
    profileForm.image = response.data.url
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error(response.message || '头像上传失败')
  }
}

// 头像上传前验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('头像图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 提交个人信息修改
const handleSubmit = async () => {
  if (!profileFormRef.value) return

  try {
    await profileFormRef.value.validate()
    loading.value = true

    const token = localStorage.getItem('Token')
    if (!token) {
      ElMessage.error('未登录或登录已过期')
      return
    }

    // 构建提交数据，只包含可修改的字段
    const updateData = {
      name: profileForm.name,
      phone: profileForm.phone,
      image: profileForm.image
    }

    console.log('更新个人信息，请求数据:', updateData)

    const response = await fetch('http://localhost:8080/employee/profile', {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Token': token
      },
      body: JSON.stringify(updateData)
    })

    if (response.status === 401) {
      localStorage.removeItem('Token')
      localStorage.removeItem('user')
      window.location.href = '/login'
      return
    }

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const result = await response.json()
    console.log('更新个人信息响应:', result)

    if (result.code === 200) {
      ElMessage.success('个人信息更新成功')

      // 更新localStorage中的用户信息
      const userData = localStorage.getItem('user')
      if (userData) {
        try {
          const user = JSON.parse(userData)
          // 更新修改的字段
          user.name = profileForm.name
          user.phone = profileForm.phone
          user.image = profileForm.image

          // 保存回localStorage
          localStorage.setItem('user', JSON.stringify(user))
          console.log('已更新localStorage中的用户信息:', user)
        } catch (error) {
          console.error('更新localStorage失败:', error)
        }
      }
    } else {
      ElMessage.error(result.message || '更新个人信息失败')
    }
  } catch (error) {
    console.error('修改个人信息失败:', error)
    ElMessage.error('修改失败，请重试')
  } finally {
    loading.value = false
  }
}

// 重置表单
const handleReset = () => {
  // 重新从localStorage加载原始数据
  initFormData()
  ElMessage.info('表单已重置为原始数据')
}

// 修改密码
const handlePasswordSubmit = async () => {
  if (!passwordFormRef.value) return

  try {
    await passwordFormRef.value.validate()
    passwordLoading.value = true

    const token = localStorage.getItem('Token')
    if (!token) {
      ElMessage.error('未登录或登录已过期')
      return
    }

    const passwordData = {
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    }

    console.log('修改密码，请求数据:', { ...passwordData, oldPassword: '***', newPassword: '***' })

    const response = await fetch('http://localhost:8080/employee/password', {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Token': token
      },
      body: JSON.stringify(passwordData)
    })

    if (response.status === 401) {
      localStorage.removeItem('Token')
      localStorage.removeItem('user')
      window.location.href = '/login'
      return
    }

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const result = await response.json()
    console.log('修改密码响应:', result)

    if (result.code === 200) {
      ElMessage.success('密码修改成功')
      handlePasswordDialogClose()
    } else {
      ElMessage.error(result.message || '修改密码失败')
    }
  } catch (error) {
    console.error('修改密码失败:', error)
    ElMessage.error('修改密码失败，请重试')
  } finally {
    passwordLoading.value = false
  }
}

// 关闭密码修改对话框
const handlePasswordDialogClose = () => {
  showPasswordDialog.value = false
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  if (passwordFormRef.value) {
    passwordFormRef.value.clearValidate()
  }
}

onMounted(() => {
  initFormData()
})
</script>

<style scoped>
.page-container {
  padding: 20px;
}

.page-container h1 {
  color: #2c3e50;
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 20px;
}

.content-card {
  background: white;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  max-width: 800px;
}

.profile-form .el-form-item {
  margin-bottom: 20px;
}

.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  display: block;
  object-fit: cover;
}

.avatar-uploader .el-upload {
  border: 2px dashed #dcdfe6;
  border-radius: 50%;
  cursor: pointer;
  width: 100px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}
</style>
